// npm i -g supervisor
const http = require('http')
const conf = require('./config/defaultConfig')
const chalk = require('chalk')
const path = require('path')
const route = require('./handle/route')
const openUrl = require('./handle/openUrl')

class Server {
	constructor(config) {
		this.conf = Object.assign({}, conf, config)
	}

	start() {
		const root = this.conf.root
		const port = this.conf.port
		const hotName = this.conf.hotName

		const server = http.createServer((req, res) => {
			const url = decodeURIComponent(req.url)
			const filePath = path.join(root, url)
			route(req, res, filePath, this.conf)
		})

		server.listen(port, hotName, () => {
			const adr = `http://${hotName}:${port}`
			console.info(`Server start at ${chalk.green(adr)}`)
			openUrl(adr)
		})
	}
}

module.exports = Server
